package com.sk.sourcecircle.activity.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.community.CommunityFragment;
import com.sk.sourcecircle.activity.community.fragment.ChatFragment;
import com.sk.sourcecircle.activity.find.FindFragment;
import com.sk.sourcecircle.activity.home.HomeFragment;
import com.sk.sourcecircle.activity.home.activity.ReleaseAlbumActivity;
import com.sk.sourcecircle.activity.home.activity.SearchToAddActivity;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.activity.mine.MineFragment;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.dialog.ReleaseDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.MyCity;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, EMMessageListener {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_find)
    RadioButton rbFind;
    @BindView(R.id.rb_community)
    RadioButton rbCommunity;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.tv_release)
    TextView tvRelease;

    HomeFragment homeFragment;
    FindFragment findFragment;
    CommunityFragment communityFragment;
    MineFragment mineFragment;
    private String aresJson;
    private boolean vibrate;

    private float lat, lng;

    private String city;

    private static final int GROUP = 10;

    private static final int MINE = 11;

    private static final int RELEASE = 12;

    private int pos;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            Log.v("AMapLocationListener", JSON.toJSONString(aMapLocation));
            Log.v("AMapLocationListener", lat + "");
            Log.v("AMapLocationListener", lng + "");

            lat = (float) aMapLocation.getLatitude();
            lng = (float) aMapLocation.getLongitude();

            MyApplication.getInstance().setLat(lat);
            MyApplication.getInstance().setLng(lng);

            city = aMapLocation.getCity();
            MyApplication.getInstance().setCityName(city);

            SPUtils.put(mContext, "cityName", city);

            for (MyCity myCity : list) {
                if (city.contains(myCity.getCity_name()) || myCity.getCity_name().contains(city)) {
                    String cityId = myCity.getCity_id();
                    MyApplication.getInstance().setCityId(cityId);
                    homeFragment.setSwitchCity(city, cityId);
                    findFragment.setSwitchCity(city);
                    Log.v("city", cityId);
                    break;
                }
            }
        }
    };
    private List<MyCity> list = new ArrayList<>();
    private EMMessage[] messages;

    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private EMConversation conversation;

    public float getLat() {
        return lat;
    }

    public void setLat(float lat) {
        this.lat = lat;
    }

    public float getLng() {
        return lng;
    }

    public void setLng(float lng) {
        this.lng = lng;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city, String city_id) {
        this.city = city;
        homeFragment.setSwitchCity(city, city_id);
        findFragment.setSwitchCity(city);
    }


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //初始化AMapLocationClientOption对象

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init_fragment();
        initListeners();

        playBeep = true;

        initBeepSound();
        vibrate = true;
        InputStream is = getResources().openRawResource(R.raw.area);
        try {
            aresJson = readTextFromSDcard(is);
            list = JSONObject.parseArray(aresJson, MyCity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        EMClient.getInstance().chatManager().addMessageListener(this);

        MainActivityPermissionsDispatcher.startLocationWithPermissionCheck(this);
    }

    @NeedsPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})
    void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        mLocationOption = new AMapLocationClientOption();

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        //获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(true);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        mLocationOption.setNeedAddress(true);

        mLocationOption.setHttpTimeOut(20000);

//关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        mLocationClient.startLocation();

    }


    // 向用户说明为什么需要这些权限（可选）
    @OnShowRationale({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("源圈需要使用您的位置！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @OnPermissionDenied({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @OnNeverAskAgain({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(this)
                .setMessage("您已禁止定位权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    public String getAresJson() {
        return aresJson;
    }

    public void setAresJson(String aresJson) {
        this.aresJson = aresJson;
    }

    private String readTextFromSDcard(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }
        return buffer.toString();
    }

    //初始化fragment页面
    private void init_fragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        homeFragment = (HomeFragment) fm.findFragmentByTag(HomeFragment.class.getSimpleName());
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
            ft.add(R.id.fl_content, homeFragment, homeFragment.getClass().getSimpleName());
        }

        findFragment = (FindFragment) fm.findFragmentByTag(FindFragment.class.getSimpleName());
        if (findFragment == null) {
            findFragment = new FindFragment();
            ft.add(R.id.fl_content, findFragment, findFragment.getClass().getSimpleName());
        }

        communityFragment = (CommunityFragment) fm.findFragmentByTag(CommunityFragment.class.getSimpleName());
        if (communityFragment == null) {
            communityFragment = new CommunityFragment();
            ft.add(R.id.fl_content, communityFragment, communityFragment.getClass().getSimpleName());
        }

        mineFragment = (MineFragment) fm.findFragmentByTag(MineFragment.class.getSimpleName());
        if (mineFragment == null) {
            mineFragment = new MineFragment();
            ft.add(R.id.fl_content, mineFragment, mineFragment.getClass().getSimpleName());
        }


        ft.show(homeFragment);
        ft.hide(findFragment);
        ft.hide(communityFragment);
        ft.hide(mineFragment);
        ft.commit();
    }

    private void initListeners() {
        rbHome.setOnCheckedChangeListener(this);
        rbFind.setOnCheckedChangeListener(this);
        rbCommunity.setOnCheckedChangeListener(this);
        rbMine.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.rb_home:
                if (isChecked) {
                    showHome();
                }
                break;
            case R.id.rb_find:
                if (isChecked) {
                    showFind();
                }
                break;
            case R.id.rb_community:
                if (isChecked) {

                    if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                        Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivityForResult(intent, GROUP);
                        return;
                    }

                    communityFragment.refresh();
                    showCommunity();
                }
                break;
            case R.id.rb_mine:
                if (isChecked) {
                    if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                        Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivityForResult(intent, MINE);
                        return;
                    }

                    mineFragment.doRefresh();
                    showMine();
                }
                break;
        }
    }

    private void showHome() {
        pos = 1;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.show(homeFragment);
        ft.hide(findFragment);
        ft.hide(communityFragment);
        ft.hide(mineFragment);
        ft.commit();
    }

    private void showFind() {
        pos = 2;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.show(findFragment);
        ft.hide(communityFragment);
        ft.hide(mineFragment);
        ft.commit();
    }

    private void showCommunity() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.hide(findFragment);
        ft.show(communityFragment);
        ft.hide(mineFragment);
        ft.commit();
    }

    private void showMine() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.hide(findFragment);
        ft.hide(communityFragment);
        ft.show(mineFragment);
        ft.commit();
    }

    @OnClick(R.id.tv_release)
    public void onViewClicked() {
        ReleaseDialogFragment releaseDialogFragment = new ReleaseDialogFragment();
        releaseDialogFragment.setMyCallBack(MainActivity.this);
        releaseDialogFragment.show(getFragmentManager(), "release");
    }

    @Override
    public void releaseAlbum() {
        if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
            Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivityForResult(intent, MINE);
            return;
        }

        Intent intent = new Intent(mContext, ReleaseAlbumActivity.class);
        startActivity(intent);
    }

    @Override
    public void joinGroup() {
        if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
            Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivityForResult(intent, MINE);
            return;
        }

        Intent intent = new Intent(mContext, SearchToAddActivity.class);
        startActivity(intent);
    }

    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        Log.v("onMessageReceived", JSON.toJSONString(messages));
        playBeepSoundAndVibrate();
        EventBus.getDefault().post("msg");
        if (ChatFragment.handler != null) {
            ChatFragment.handler.sendEmptyMessage(1);
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        Log.v("onMessageReceived", JSON.toJSONString(messages));
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        Log.v("onMessageReceived", JSON.toJSONString(messages));
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        Log.v("onMessageReceived", JSON.toJSONString(messages));

    }

    @Override
    public void onMessageRecalled(List<EMMessage> messages) {
        Log.v("onMessageReceived", JSON.toJSONString(messages));
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
        Log.v("onMessageReceived", JSON.toJSONString(message));
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    private static final long VIBRATE_DURATION = 200L;


    @Override
    public void onBackPressed() {
        TipDialogFragment tipDialogFragment = new TipDialogFragment();
        tipDialogFragment.setContent("是否确认退出源圈？");
        tipDialogFragment.setMyCallBack(MainActivity.this);
        tipDialogFragment.show(getSupportFragmentManager(),"tip");
    }

    @Override
    public void sure() {
        super.sure();
        finish();
        System.exit(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case GROUP:
                    communityFragment.refresh();
                    showCommunity();
                    break;
                case MINE:
                    mineFragment.doRefresh();
                    showMine();
                    break;
                case RELEASE:
                    break;
            }
        } else {
            switch (pos) {
                case 1:
                    rbHome.setChecked(true);
                    break;
                case 2:
                    rbFind.setChecked(true);
                    break;
            }
        }
    }
}
